package com.alpha.gateway.config;

import com.alpha.core.http.AlphaHttpContext;
import com.alpha.core.utils.StringUtil;
import com.alpha.gateway.utils.RequestUtil;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * 自定义限流标志的 key，只会有一个 KeyResolver 生效，建议使用根据 ip 地址限流的方式
 *
 * @author chenruwan
 * @since 2022-01-01
 */
@Configuration
public class KeyResolverConfiguration {
    /**
     * 根据请求路径(URL)限流
     */
    @Bean
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 根据 ip 地址限流
     */
    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(StringUtil.nullToEmpty(RequestUtil.getRemoteIp(exchange.getRequest())));
    }

    /**
     * 根据参数限流
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(StringUtil.nullToEmpty(AlphaHttpContext.getUserId()));
    }
}
